﻿using ETA.ClientService;
using ETA.Common;
using ETA.Entity;
using ETA.IService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ETA.Web.Controllers
{
    public class FileController : Controller
    {

        private static IFileTypeService _FileTypeService { set; get; }
        private static IUploadFileService _UploadFileService { set; get; }

        public FileController(IFileTypeService IFileTypeService, IUploadFileService IUploadFileService)
        {
            _FileTypeService = IFileTypeService;
            _UploadFileService = IUploadFileService;
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult FileUpload(string fileType)
        {
            var fileTypeList = FileBll.GetFileTyes();
            var fileTypeInfo = fileTypeList.Find(f => f.FileTypeName == fileType);
            Response res = new Response();
            if (fileTypeInfo == null)
            {
                res.Result.ErrMessage = "文件类型不存在";
                return Json(res);
            }
            try
            {
                var paraFileName = Request.Params["paraFileName"];//指定文件名
                var fileId = string.Empty;
                string fileNamed = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");
                var httpfile = Request.Files["Filedata"];
                string fileName = httpfile.FileName;
                string fileExtension = fileName.Substring(fileName.LastIndexOf('.') + 1);
                var newFileName = fileNamed + "." + fileExtension;
                string uploadsFolder = HttpContext.Server.MapPath("~/"+fileTypeInfo.UploadPath);

                if (httpfile != null)
                {
                    if (!CheckFileType(fileExtension,fileTypeInfo.FileExt))
                    {
                        res.Result.IsSuccess = false;
                        res.Result.ErrMessage = "不支持格式" + fileExtension;
                        return Json(res);
                    }
                    var uploadsPath = Path.Combine(uploadsFolder, fileNamed + "." + fileExtension);
                    httpfile.SaveAs(uploadsPath);
                    //文件保存
                    var addFileInfoRes = AddFileInfo(newFileName, fileTypeInfo);
                    if (!addFileInfoRes.Result.IsSuccess)
                    {
                        return Json(res);
                    }
                    else
                    {
                        fileId = addFileInfoRes.UploadFile.UploadFileId;
                        res.Result.IsSuccess = true;
                        res.Result.Message = fileId;// fileNamed + "." + fileExtension;//点号传参有问题
                    }
                    //
                }
                else
                {
                    res.Result.IsSuccess = false;
                    res.Result.ErrMessage = "没有文件";
                }
            }
            catch (Exception e)
            {
                res.Result.IsSuccess = false;
                res.Result.ErrMessage = e.Message;
            }
            return Json(res);
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileTypeInfo"></param>
        /// <returns></returns>
        private CreateUploadFileResponse AddFileInfo(string fileName, FileType fileTypeInfo)
        {
            var res = new CreateUploadFileResponse();
            var createUploadFileRequest = new CreateUploadFileRequest
            {
                UploadFile = new Entity.UploadFile
                {
                    FileType = fileTypeInfo,
                    FileName = fileName,
                    UploadFileId = Guid.NewGuid().ToString(),
                    IsDelete = false
                }
            };
            res = _UploadFileService.CreateUploadFile(createUploadFileRequest);

            return res;
        }
        /// <summary>
        /// 检测上传文件格式是否合法
        /// </summary>
        /// <param name="ext"></param>
        /// <returns></returns>
        private bool CheckFileType(string ext,string fileExts)
        {
            var FileExtArr = fileExts.Split('#');
            return FileExtArr.Any(a => a.IndexOf(ext.ToLower()) > -1);
        }

        /// <summary>
        /// 获取头像信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FileContentResult GetPic(string id)
        {
            try
            {
                byte[] bytes = null;
                var file = FileBll.GetFileById(id);
                var uploadsFolder = HttpContext.Server.MapPath("~"+file.FileType.UploadPath);
                var filePath = Path.Combine(uploadsFolder, file.FileName);
                bytes = System.IO.File.ReadAllBytes(filePath);
                return File(bytes, @"image/jpeg");
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
